package com.mxf.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : [mxf]
 * @version : [v1.0]
 * @className : MyLB
 * @description : [描述说明该类的功能]
 * @createTime : [2022/9/30 11:14]
 * @updateUser : [mxf]
 * @updateTime : [2022/9/30 11:14]
 * @updateRemark : [描述说明本次修改内容]
 */
//@Component
public class MyLB implements LoadBalancer{

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement()
    {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        }while(!this.atomicInteger.compareAndSet(current,next));
        System.out.print("*****第几次访问，次数next: "+next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {

        int index = getAndIncrement() % serviceInstances.size();
        ServiceInstance serviceInstance = serviceInstances.get(index);
        System.out.println("，调用地址是：" + serviceInstance.getUri());
        return serviceInstance;
    }
}
